<?php

namespace Install\Controller;

use Think\Controller;
use Think\Db;

/**
 * 安装控制器
 * @author
 */
class IndexController extends Controller
{
    protected function _initialize()
    {
        if (is_file('./data/install.lock')) {
            $msg = '您已经安装过吉他郭问答系统，重新安装需要先删除 ./data/install.lock 文件';
            $this->error($msg, 'index.php');
        }
    }

    //安装首页
    public function index()
    {
        $this->display();
    }

    //安装第一步，检测运行所需的环境设置
    public function step1()
    {
        $this->assign('dirfile', check_dirfile());
        $this->assign('env', check_env());
        $this->assign('func', check_func());
        $this->display();
    }

    //安装第二步，创建数据库
    public function step2()
    {
        if (check_install_err()) {
            $this->error('环境检测没有通过，请调整环境后重试！');
        }
        if (IS_POST) {
            //检测数据库配置
            $db_host   = I('request.db_host', '', 'trim');
            $db_user   = I('request.db_user', '', 'trim');
            $db_pwd    = I('request.db_pwd', '', 'trim');
            $db_name   = I('request.db_name', '', 'trim');
            $db_prefix = I('request.db_prefix', '', 'trim');
            $db_port   = I('request.db_port', '', 'trim');

            $username   = I('request.username', '', 'trim');
            $password   = I('request.password', '', 'trim');
            $repassword = I('request.repassword', '', 'trim');
            $mobile     = I('request.mobile', '', 'trim');

            if (empty($db_host) || empty($db_user) || empty($db_name) || empty($db_prefix) || empty($db_port)) {
                $this->error('请填写完整的数据库配置');
            }
            if (empty($username) || empty($password) || empty($repassword) || empty($mobile)) {
                $this->error('请填写完整管理员信息');
            }
            $len = mb_strlen($username, 'utf8');
            if ($len < 3 || $len > 18) {
                $this->error('用户名长度为3-18位');
            }
            if ($password <> $repassword) {
                $this->error('两次输入的密码不一致');
            }
            if (!preg_match("/^1[23456789]{1}\d{9}$/", $mobile)) {
                $this->error('手机号格式错误');
            }
            $install_admin['username'] = $username;
            $install_admin['password'] = $password;
            $install_admin['mobile']   = $mobile;
            session('install_admin', $install_admin);


            $db_type           = C('INSTALL_DB_TYPE');
            $db_charset        = C('INSTALL_DB_CHARSET');
            $install_db_config = array(
                'db_type'    => $db_type,
                'db_user'    => $db_user,
                'db_pwd'     => $db_pwd,
                'db_host'    => $db_host,
                'db_port'    => $db_port,
                'db_name'    => $db_name,
                'db_charset' => $db_charset,
                'db_prefix'  => $db_prefix,
            );
            session('install_db_config', $install_db_config);
            unset($install_db_config['db_name']);
            $db = Db::getInstance($install_db_config);
            try {
                $sql = "CREATE DATABASE IF NOT EXISTS `{$db_name}` DEFAULT CHARACTER SET utf8";
                $db->execute($sql);
            } catch (\Exception $e) {
                $this->error('数据库连接失败！');
            }
            //数据库配置文件
            $content = '<?' . "php\n";
            $content .= "return array (\n";
            $content .= "'DB_TYPE'=> '{$install_db_config['db_type']}',\n";
            $content .= "'DB_HOST'=> '{$install_db_config['db_host']}',\n";
            $content .= "'DB_NAME'=> '{$db_name}',\n";
            $content .= "'DB_USER'=> '{$install_db_config['db_user']}',\n";
            $content .= "'DB_PWD'=> '{$install_db_config['db_pwd']}',\n";
            $content .= "'DB_PORT'=> '{$install_db_config['db_port']}',\n";
            $content .= "'DB_PREFIX'=> '{$install_db_config['db_prefix']}',\n";
            $content .= "'DB_CHARSET'=> '{$install_db_config['db_charset']}',\n";
            $content .= "'DB_DEBUG'=> true,\n";
            $content .= ");";
            $fp      = @fopen(APP_PATH . 'Common/Conf/db.php', 'wb+');
            if (!$fp) {
                $this->error('打开配置文件失败');
            }
            if (!@fwrite($fp, trim($content))) {
                $this->error('写入配置文件失败');
            }
            @fclose($fp);
            //数据库配置文件end
            $this->redirect('step3');
        } else {
            $this->display();
        }
    }

    //安装第三步，安装数据表，创建配置文件
    public function step3()
    {
        if (check_install_err()) {
            $this->error('环境检测没有通过，请调整环境后重试！');
        }
        $install_db_config = session('install_db_config');
        C($install_db_config);
        $db                = Db::getInstance($install_db_config);
        ob_end_clean();
        $content = '<?' . "php\n";
        $content .= "return array (\n";
        $content .= "'YTATA_VERSION'=>'" . C('INSTALL_YTATA_VERSION') . "',\n";
        $content .= "'YTATA_UPDATE_TIME'=>'" . C('INSTALL_UPDATE_TIME') . "',\n";
        $content .= ");";
        $fp      = @fopen(APP_PATH . 'Common/Conf/version.php', 'wb+');
        if (!$fp) {
            $this->error('打开版本文件失败');
        }
        if (!@fwrite($fp, trim($content))) {
            $this->error('写入版本文件失败');
        }
        @fclose($fp);
        if (!$fp_structure = @fopen(APP_PATH . 'install/Data/sql-structure.sql', 'rb')) {
            $this->error('打开文件sql-structure.sql出错，请检查文件是否存在');
        }
        if (!$fp_data = @fopen(APP_PATH . 'install/Data/sql-data.sql', 'rb')) {
            $this->error('打开文件sql-data.sql出错，请检查文件是否存在');
        }
        $install_admin = session('install_admin');
        $domain_url    = 'http://' . $_SERVER['SERVER_NAME'] . __ROOT__ . '/';
        $this->assign('domain', $domain_url);
        $this->assign('mobile', $install_admin['mobile']);
        $this->assign('v', C('INSTALL_YTATA_VERSION'));
        $this->display();
        installing_javascript("数据库[{$install_db_config['db_name']}]创建成功！...");
        installing_javascript("数据库配置文件db.php创建成功！...");
        $query = '';
        while (!feof($fp_structure)) {
            $line = rtrim(fgets($fp_structure, 1024));
            if (strstr($line, '||-_-||') != false) {
                $line = ltrim(rtrim($line, "||-_-||"), "||-_-||");
                $line = str_replace(C('INSTALL_DB_PRE'), $install_db_config['db_prefix'], $line);
                installing_javascript("建立数据表 " . $line . "...成功");
            } else {
                if (preg_match('/;$/', $line)) {
                    $query .= $line . "\n";
                    $query = str_replace(C('INSTALL_DB_PRE'), $install_db_config['db_prefix'], $query);
                    //echo $query."<br>";
                    //exit();
                    $db->execute($query);
                    $query = '';
                } else if (!ereg('/^(//|--)/', $line)) {
                    $query .= $line;
                }
            }
        }
        @fclose($fp_structure);
        //
        installing_javascript("所有数据表创建完成...成功");
        $query = '';

        while (!feof($fp_data)) {
            $line = rtrim(fgets($fp_data, 1024));
            if (ereg(";$", $line)) {
                $query .= $line;
                $query = str_replace(C('INSTALL_DB_PRE'), $install_db_config['db_prefix'], $query);
                $db->execute($query);
                $query = '';
            } else if (!ereg("^(//|--)", $line)) {
                $query .= $line;
            }
        }
        @fclose($fp_data);
        installing_javascript("基础数据创建完成...成功");
        $install_admin = session('install_admin');
        $reg           = D('User')->user_reg($install_admin['username'], $install_admin['mobile'],'', $install_admin['password']);
        if ($reg['status'] == 1) {
            $map['isadmin'] = 1;
            $map['auth']    = 'all';
            $map['uid']     = 1;
            M('User')->save($map);
            installing_javascript("超级管理员账号创建完成...成功");
        }
        //修改配置信息的网站域名
        unset($map);
        $map['value'] = 'http://' . $_SERVER['SERVER_NAME'];
        $map['id']    = 2;
        M('Config')->save($map);
        ytata_refresh_cache('config');
        installing_javascript("系统配置文件生成ytata.php...成功");
        //修改导航首页的链接地址
        unset($map);
        $map['url'] = 'http://' . $_SERVER['SERVER_NAME'] . __ROOT__ . '/';
        $map['id']  = 1;
        M('Nav')->save($map);
        installing_javascript("导航更新完成...成功");
        sleep(2);
        $this->redirect('complete');
    }

    //安装完成
    public function complete()
    {
        //写入安装锁定文件

        if (is_writable('./data/')) {
            $fp = @fopen('./data/install.lock', 'wb+');
            fwrite($fp, 'OK');
            fclose($fp);
        }
        $this->display();
    }
}